package com.zpf.service.impl;

import com.zpf.dao.OrderDao;
import com.zpf.dao.OrderDetailDao;
import com.zpf.dao.impl.OorderDetailDaoImpl;
import com.zpf.dao.impl.OrderDaoImpl;
import com.zpf.pojo.Cart;
import com.zpf.pojo.Order;
import com.zpf.pojo.OrderDetail;
import com.zpf.service.CartService;
import com.zpf.service.OrderService;
import com.zpf.utils.RandomUtils;
import com.zpf.utils.TxUtils;

import java.sql.Connection;
import java.util.Date;
import java.sql.SQLException;
import java.util.List;

public class OrderServiceImpl implements OrderService {

    CartService cartService = new CartServiceImpl();
    OrderDao orderDao = new OrderDaoImpl();
    OrderDetailDao orderDetailDao = new OorderDetailDaoImpl();

   //添加订单
    /*
    * 生成一条订单记录
    * 添加订单详情
    * 删除购物车记录
    *
    * */

    @Override
    public Order addOrder(int uid, String aid) {


        Connection conn = TxUtils.getConn();
        try {
           conn.setAutoCommit(false);
           //获取该用户的购物车信息
            List<Cart> carts = cartService.findCartByUid(uid);
            double sum = 0;
            //求订单总额
            for (Cart cart : carts) {
                sum += cart.getMoney();
            }

            Order order = new Order();
            //设置订单id
           order.setId(RandomUtils.createActive());
           order.setUid(uid);
            //订单总额
           order.setMoney(sum);
           order.setStatus("未支付");
           order.setTime(new Date());
           order.setAid(Integer.parseInt(aid));

            orderDao.insert(order);
            //增加订单详情
            //一个购物车商品对应一个订单详情
            for (Cart cart : carts) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOid(order.getId());
                orderDetail.setPid(cart.getPid());
                orderDetail.setNum(cart.getNum());
                orderDetail.setMoney(cart.getMoney());

                orderDetailDao.insert(orderDetail);
            }

        //删除购物车记录(清空购物车)
            cartService.clearCart(uid);



           conn.commit();
           return order;
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            System.out.println("添加订单失败");
        } finally {
            try {
                TxUtils.remove();
                conn.setAutoCommit(true);
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public void paySuccess(Order order) {
        orderDao.paySuccess(order);
    }
}
